require "trifle/ruby/queue/redis_connect"
require "json"

module Trifle
	module Ruby
		class AppTransaction
			attr_accessor :app_type, :request_id, :trace, :user_agent, :ipv4, :url, :location, :environment, :server, :finished_at

			def initialize(request_id)
				@app_type = "transaction"
				@request_id = request_id
				@trace = []
				@url = url
			end

			def self.current
				Thread.current["trifle-transaction"]
			end

			def current!
				Thread.current["trifle-transaction"] = self
			end

			def complete!
				@environment = ::Rails.env || ENV["rack_env"] || ENV["RAILS_ENV"]
				config = Config.load[@environment]
				return unless config
				@finished_at = Time.now.to_f
				@server = {}
				begin
					memory = `ps -o rss -p #{Process.pid}`.chomp.split("\n").last.strip.to_i / 1024
					@server[:process_id] = Process.pid
					@server[:memory] = memory.to_i
					@server[:host] = Socket.gethostname
					@server[:ip] = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
				rescue => e
					@server[:process_id] = Process.pid
					@server[:memory] = 0
					@server[:host] = "localhost"
					@server[:ip] = "127.0.0.1"
					Logger.error "Unable to get memory, host & IP address information."
				end

				if config["queue"]["enabled"] and config["queue"]["handler"] == "redis"
					redis_connect = Trifle::Ruby::Queue::RedisConnect.new
					redis_connect.push(self.to_json)
				else
					Trifle::Ruby::Handler.submit!("transactions", [self].to_json)
				end
			end
		end
	end
end
